package com.chocus.core.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.chocus.common.utils.RequestUtils;
import com.chocus.core.bean.BuyerCart;
import com.chocus.core.bean.BuyerItem;
import com.chocus.core.bean.order.Order;
import com.chocus.core.service.buyer.BuyerService;
import com.chocus.core.service.buyer.SessionProvider;

import redis.clients.jedis.Jedis;

@Controller
@RequestMapping("/buyer/")
public class BuyerController {

	private static final String MODEL_PATH = "product/";
	@Autowired
	private SessionProvider sessionProvider;
	@Autowired
	private BuyerService buyerService;

	/**
	 * 结算
	 * 
	 * @return
	 */
	@RequestMapping("trueBuy")
	public String trueBuy(HttpServletRequest request, HttpServletResponse response, Model model) {

		// 从redis中取回商品
		String username = sessionProvider.getAttribute(RequestUtils.getCSESSIONID(request, response));
		BuyerCart buyerCart = buyerService.getBuyerCartFromRedis(username);
		// 定义标记，如果购物车中有任意一款商品没货则认为库存不足
		boolean flag = false;
		// 判断购物车是否为空
		if (buyerCart.getItems() != null && buyerCart.getItems().size() > 0) {
			List<BuyerItem> items = buyerCart.getItems();
			if (items != null && items.size() > 0) {
				for (BuyerItem buyerItem : items) {
					buyerItem.setSku(buyerService.putDataToBuyerCart(buyerItem));
					if (buyerItem.getAmount() > buyerItem.getSku().getStock()) {
						buyerItem.setIsHave(false);
						flag = true;
					}
				}
				if (flag) {
					// 不充足则重定向会购物车，显示库存不足的商品
					model.addAttribute("buyerCart", buyerCart);
					return MODEL_PATH + "cart";
				}
			}
		} else {
			// 为空则跳转回购物车
			return "redirect:/product/toCart";
		}
		return MODEL_PATH + "productOrder";
	}

	/**
	 * 提交订单
	 * 
	 * @param order
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("confirmOrder")
	public String confirmOrder(Order order, HttpServletRequest request, HttpServletResponse response) {
		String username = sessionProvider.getAttribute(RequestUtils.getCSESSIONID(request, response));
		buyerService.saveOrder(order, username);
		return MODEL_PATH + "confirmOrder";
	}
}
